<template>
  <a-card title="个人设置" style="width: 100%">
    <template v-slot:tabBarExtraContent><a href="#">more</a></template>
    <a-row>
      <a-col :span="12">
        <a-form
          ref="userFromRef"
          :model="user"
          :rules="rules"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <a-form-item label="编号">
            <a-input disabled v-model:value="user.id" />
          </a-form-item>
          <a-form-item label="手机">
            <a-input disabled v-model:value="user.mobile" />
          </a-form-item>
          <a-form-item ref="name" label="媒体名称" name="name">
            <a-input v-model:value="user.name" />
          </a-form-item>
          <a-form-item label="媒体介绍" name="intro">
            <a-textarea v-model:value="user.intro" />
          </a-form-item>
          <a-form-item ref="email" label="邮箱" name="email">
            <a-input v-model:value="user.email" />
          </a-form-item>
          <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
            <a-button type="primary" @click="onSubmit">
              保存设置
            </a-button>
          </a-form-item>
        </a-form>
      </a-col>
      <a-col :span="12">
        <div class="avatar-box">
          <a-avatar class="avatar" shape="square" :src="user.photo" :size="200">
            <template v-slot:icon><UserOutlined /></template>
          </a-avatar>
          <div class="edit-box">
            <label for="file">
              Edit
            </label>
            <input
              @change="onFileChange"
              ref="fileRef"
              id="file"
              type="file"
              hidden
            />
          </div>
        </div>
      </a-col>
    </a-row>

    <a-modal
      style="width:240px"
      v-model:visible="visible"
      title="Modal"
      ok-text="确认"
      cancel-text="取消"
      @Ok="onConform"
    >
      <div class="crop-box">
        <img class="crop-image" ref="previewRef" :src="previewAvatar" alt="" />
      </div>
    </a-modal>
  </a-card>
</template>

<script>
import { useStore } from 'vuex'
import { reactive, computed, toRefs } from 'vue'

import { rules } from './validate'

import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'

import { UserOutlined } from '@ant-design/icons-vue'

import { updateUserPhoto, updateUserProfile } from '@/api/user'

export default {
  components: {
    UserOutlined
  },
  setup() {
    const labelCol = { span: 4 }
    const wrapperCol = { span: 14 }

    const store = useStore()
    const state = reactive({
      fileRef: null,
      previewRef: null,
      userFromRef: null,

      visible: false,
      previewAvatar: '',
      cropper: null,
      user: computed(() => store.state.user)
    })

    const initCrop = () => {
      // 获取裁剪图片dom
      const image = state.previewRef

      // 解决重新选择图片 预览裁剪图片不变化
      if (state.cropper) {
        return state.cropper.replace(state.previewRef)
      }
      state.cropper = new Cropper(image, {
        aspectRatio: 1 / 1 /** 比例 */,
        viewMode: 1 /** 裁剪框不能超出图片 */,
        dragMode: 'none' /** 画布不能移动 */,
        cropBoxResizable: false,
        background: false,
        crop(event) {}
      })
    }

    const onFileChange = () => {
      openModel()
      const fileRef = state.fileRef
      const blobData = window.URL.createObjectURL(fileRef.files[0])
      state.previewAvatar = blobData
      // 解决选择相同文件不触发的问题
      fileRef.value = ''
      setTimeout(() => {
        initCrop()
      }, 1000)
    }

    const onConform = () => {
      // model 确认按钮
      // 获取 裁剪结果 上传数据 更新数据
      state.cropper.getCroppedCanvas().toBlob(async file => {
        const fd = new FormData()
        fd.append('photo', file)
        // 上传数据
        console.log(fd, 'fd')
        const res = await updateUserPhoto(fd)
        hideModel()
        const { photo } = res.data
        store.commit('SET_USER', { photo })
      })
    }

    const onSubmit = () => {
      state.userFromRef
        .validate()
        .then(async () => {
          const res = await updateUserProfile(state.user)
          console.log(res)
        })
        .catch(error => {
          console.log('error', error)
        })
    }

    const openModel = () => {
      state.visible = true
    }
    const hideModel = () => {
      state.visible = false
    }

    return {
      rules,
      labelCol,
      wrapperCol,
      ...toRefs(state),

      onSubmit,
      onConform,
      onFileChange
    }
  }
}
</script>

<style scoped lang="scss">
.avatar-box {
  height: 200px;
  width: 200px;
  position: relative;
  .edit-box {
    position: absolute;
    padding: 2px 8px;
    left: 4px;
    bottom: 4px;
    border-radius: 4px;
    background-color: rgba(0, 0, 0, 0.8);
    color: #ffffff;
  }
}

.crop-box {
  height: 200px;
  width: 200px;
  .crop-images {
    max-width: 100%;
    display: block;
  }
}
</style>
